# coding: utf-8
from typing import Literal

from PySide6.QtWidgets import QLineEdit, QPlainTextEdit, QFileDialog
from qfluentwidgets import LineEdit, SmoothScrollDelegate, setFont, Action, FluentIcon as FIF
from qfluentwidgets.components.widgets.menu import TextEditMenu

from common import StyleSheet


class ElLineEdit(LineEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        StyleSheet.LINE_EDIT.apply(self)
        self.setMinimumHeight(40)
        self.setClearButtonEnabled(True)

    def paintEvent(self, e):
        QLineEdit.paintEvent(self, e)


class ElPlainTextEdit(QPlainTextEdit):
    """ Plain text edit """

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.scrollDelegate = SmoothScrollDelegate(self)
        StyleSheet.LINE_EDIT.apply(self)
        setFont(self, 14)
        self.setMinimumHeight(100)

    def contextMenuEvent(self, e):
        menu = TextEditMenu(self)
        menu.exec(e.globalPos())


class SelectLineEdit(LineEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setReadOnly(True)
        self.setPlaceholderText("选择文件")

        self.selectAction = Action(FIF.QUICK_NOTE, "", self, triggered=self.openFileDialog)
        self.addAction(self.selectAction)
        self.__type = "getFile"
        self.__filter = "All Files (*)"

    def setType(self, tp: Literal["getFile", "folder", 'setFile']):
        self.__type = tp
        if tp in ["getFile", "setFile"]:
            self.selectAction.setIcon(FIF.QUICK_NOTE)
            self.setPlaceholderText("选择文件")
        else:
            self.selectAction.setIcon(FIF.FOLDER)
            self.setPlaceholderText("选择文件夹")

    def getType(self):
        return self.__type

    def setFilter(self, filter_: str):
        self.__filter = filter_

    def getFilter(self):
        return self.__filter

    def openFileDialog(self):
        if self.__type == "getFile":
            file_path, _ = QFileDialog.getOpenFileName(self, "选择文件", "", self.__filter)
        elif self.__type == "setFile":
            file_path, _ = QFileDialog.getSaveFileName(self, "保存文件", "", self.__filter)
        else:
            file_path = QFileDialog.getExistingDirectory(self, "选择文件夹", "")
        if file_path:
            self.setText(file_path)
